package edu.nf.redismqes.service;

import edu.nf.redismqes.model.docmentt.NewDoc;
import edu.nf.redismqes.model.entity.New;
import edu.nf.redismqes.mappers.newsMapper;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ Author bin
 * @ Create  2025/10/22 上午10:03
 * 索引初始化 把mysql的数据导入到es中
 **/
@Service
public class EsInit {
    private static final String ES_INIT_KEY = "es:init:news";

    @Autowired
    private RedisTemplate<String, Boolean> redisTemplate;

    @Autowired
    private ElasticsearchOperations operations;

    @Autowired
    private newsMapper newMapper;

    @PostConstruct
    public void init() {
        // 1. 先检查 Redis 是否存在标记
        Boolean isInIt = redisTemplate.opsForValue().get(ES_INIT_KEY);
        if (Boolean.TRUE.equals(isInIt)) {
            System.out.println("ES 已初始化，跳过同步");
            return;
        }

        // 2. 检查索引是否存在（冗余安全）
        if(!operations.indexOps(NewDoc.class).exists()) {
            operations.indexOps(NewDoc.class).create();
            System.out.println("创建索引成功");
        } else {
            System.out.println("索引已存在");
        }

        // 3. 同步 MySQL 数据
        List<New> news= newMapper.selectAll();

        List<NewDoc> docs = news.stream()
                .map(this::convertToDoc)
                .collect(Collectors.toList());
        operations.save(docs);

        // 4. 同步完成后，写入 Redis 标记
        redisTemplate.opsForValue().set(ES_INIT_KEY, Boolean.TRUE);

        System.out.println("ES 初始化完成，MySQL 数据已同步");
    }

    private NewDoc convertToDoc(New news) {
        NewDoc doc = new NewDoc();
        doc.setId(news.getId());
        doc.setTitle(news.getTitle());
        doc.setAuthor(news.getAuthor());
        doc.setType(news.getType());
        doc.setContent(news.getContent());
        return doc;
    }
}
